#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdlib.h>
#include <strings.h>
#include <functional>
#include <string.h>
#include <string>
#include <stdio.h>
#include <unordered_map>
#include "Log.hpp"

using namespace std;

typedef function<string(string)> Func_t;

Log lg;

#define DefaultIp "0.0.0.0"
#define DefaultPort 8080
#define SIZE 1024

enum
{
    Socketerr = 1,
    Binderr
};

class UdpServer
{
public:
    UdpServer(uint16_t port = DefaultPort, std::string ip = DefaultIp)
        : port_(port),
          ip_(ip)
    {
    }

    void Init()
    {
        sock_ = socket(AF_INET, SOCK_DGRAM, 0);
        if (sock_ < 0)
        {
            lg(Fatal, "socket fail,sock:%d,code:%d,errno:%s", sock_, errno, strerror(errno));
            exit(Socketerr);
        }
        lg(Info, "socket success,sock:%d", sock_);

        struct sockaddr_in local;
        bzero(&local, sizeof(local));

        local.sin_family = AF_INET;
        local.sin_port = htons(port_);
        local.sin_addr.s_addr = htonl(inet_addr(ip_.c_str()));
        socklen_t len = sizeof(local);

        int n = bind(sock_, (const sockaddr *)&local, len);
        if (n != 0)
        {
            lg(Fatal, "bind fail,code:%n,errno:%d", n, strerror(errno));
            exit(Binderr);
        }
        lg(Info, "bind success,code:%d", n);
    }

    void Check(const sockaddr_in &client, std::unordered_map<std::string, sockaddr_in> &unmap, const string &ip, const uint16_t &port)
    {
        for (const auto &e : unmap)
        {
            if (e.first == ip)
            {
                return;
            }
        }
        unmap[ip] = client;
        printf("welcome [%s]:[%d] join the group.\n", ip.c_str(), port);
    }

    void Sendmessage(const std::unordered_map<std::string, sockaddr_in> &unmap, const string &str, const string &ip, const uint16_t &port)
    {
        for (const auto &e : unmap)
        {
            socklen_t len = sizeof(e);
            string message="[";
            message+=ip;
            message+="]#"+str;
            sendto(sock_, message.c_str(), message.size(), 0, (const sockaddr *)&(e.second), len);
        }
    }

    void Run(Func_t func)
    {
        char buf[SIZE];
        flag_ = true;
        std::unordered_map<std::string, sockaddr_in> sock_unmap;

        while (flag_)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            //std::cout << "Server get a message:";
            int n = recvfrom(sock_, buf, sizeof(buf), 0, (struct sockaddr *)&client, &len);
            if (n < 0)
            {
                continue;
            }
            //std::cout << buf << std::endl;
            uint16_t port = ntohs(client.sin_port);
            char ipbuffer[32];
            inet_ntop(AF_INET, &client.sin_addr.s_addr, ipbuffer, sizeof(ipbuffer));
            Check(client, sock_unmap, ipbuffer, port);
            //回调函数
            // std::string s="Server#";
            // s+=buf;
            //std::string ref = func(buf);

            Sendmessage(sock_unmap, buf,ipbuffer,port);
             memset(buf,0,sizeof(buf));
        }
    }

    ~UdpServer()
    {
    }

private:
    uint16_t port_;
    std::string ip_;
    bool flag_ = false;
    int sock_;
};
